<?php
ini_set('session.use_trans_sid', 1);
header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
session_start();
require_once('fb/src/facebook.php');


// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
  'appId'  => '121250027990936',
  'secret' => '083fde4c54450e0d32ece4e7715c8610',
));

// Get User ID
$user = $facebook->getUser();
	

if ($user) {
  try {
    // Proceed knowing you have a logged in user who's authenticated.
    $user_profile = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
    $user = null;
  }
}



if ($user) {
  $logoutUrl = $facebook->getLogoutUrl(array( 'next' => 'http://gausipp.roopunk.com/'));
} else {
  $loginUrl = $facebook->getLoginUrl(array( 'scope' => 'email'));
}

     //print_r($_SESSION); 

 //and put the extra condition to check if its a male or a female


	if(isset($_GET['action']) && $_GET['action']=="logout")
		{
		session_destroy();
		// this the culprit for now. It is taking to the facebook page after logout.
		if($user)  echo '<script>window.location = "'.$logoutUrl.'"; </script>';
		echo '<script>window.location="index.php";</script>';		
		}
	else if(isset($_GET['action']) && $_GET['action']=="login")
	{
		if(isset($_SESSION['user']) && !isset($_GET['refid'])) // already logged in 
		{
			echo '<script>window.location = "index.php"; </script>';
		}
		else
		{
			if($user)// && $user_profile['gender']=="female")  // if user is logged in to facebook
			{
				date_default_timezone_set('Asia/Calcutta');
				require_once("php/connection.php"); 

				// for alias users, the email id will be of the culprits
				if($user == "1708351521")
				$user_email = "rishabhbansal0@gmail.com";
				else
				$user_email = $user_profile['email'];
				
				
				
				//setting the name
				if($user == "1708351521")
					$_SESSION['name'] = "Emily Manson";
				else
					$_SESSION['name'] = $user_profile["name"];
					
					
					
				//check if already in our list
				$result = mysql_query("SELECT * FROM site_user_meta WHERE `fbid`='$user'");
				if(!$result)  echo '<script>alert("'.mysql_error().'");</script>';
				
				if(mysql_numrows($result) == 0) 
				{
					$user_name = $_SESSION['name'];
					$result = mysql_query("INSERT INTO site_user_meta(`fbid`,`name`,`email`) VALUES('$user','$user_name','$user_email')");
					if(!$result) echo  mysql_error();		
					
					// processing referral id
					if(isset($_GET['refid']))
					{
						$ref_fbid = $_GET['refid'];
						$temp1 = mysql_query("SELECT * FROM site_invite WHERE `fbid`='$user' AND `ref_fbid`='$ref_fbid'");
						if(mysql_numrows($temp1) == 0)
						{
							$temp = mysql_query("INSERT INTO site_invite (`fbid`,`ref_fbid`) VALUES('$user','$ref_fbid')");
							if(!$temp) die(mysql_error());
						
							$temp = mysql_query("UPDATE site_user_meta SET points=points+5 WHERE `fbid`='$ref_fbid'");
							if(!$temp) die(mysql_error());
						}
					}
				}
				
				// updating email				
				
				$temp = mysql_query("SELECT * FROM site_user_meta WHERE `fbid`='$user' AND `email`=''");
				if(mysql_numrows($temp)!=0)
				{
					$temp1 = mysql_query("UPDATE site_user_meta SET `email`='$user_email' WHERE `fbid`='$user'");
					if(!$temp1) die(mysql_error());
				}
				
				
				//	print_r($user_profile);
			
		
				// inserting the last login time
				$time = time();
				$session_id = session_id();
				$result1 = mysql_query("INSERT INTO site_user_login(`session_id`,`fbid`,`time`,`time_out`) VALUES('$session_id','$user','$time','$time')");
				if(!$result1) echo  mysql_error();
		
				//setting the nick name
				/*
				$result2 = mysql_query("SELECT * FROM site_user_meta WHERE `fbid`='$user'");
				$nick_name = mysql_result($result2, 0, 'nick_name');
				$_SESSION['nick_name'] = $nick_name;
				*/
			
				//define all the session values
				$_SESSION['user'] = $user;
				$user_friends = $facebook->api('/me/friends');
				$_SESSION['friends'] = $user_friends;
			
				//the session is set, head back to index.php	

				if(isset($_GET['gurl']))
					$gurl =	$_GET['gurl'];
				if($gurl == "")
					echo '<script>window.location = "index.php"; </script>';
				else
				{
				echo '<script>
				var url = decodeURIComponent("'.$gurl.'");
				window.location = url; 
				</script>';
				}
				
			}
			/*else if($user && $user_profile['gender']!="female")
			{
				
				date_default_timezone_set('Asia/Calcutta');
				$time = time();
				$gender = $user_profile['gender'];
				require_once("php/connection.php"); 
			
				//check if already in our list
				$result = mysql_query("SELECT * FROM site_boys WHERE `fbid`='$user'");
				if(mysql_numrows($result) == 0) 
				{
				$result = mysql_query("INSERT INTO site_boys (`fbid`,`time`,`gender`) VALUES('$user','$time','$gender')");
				if(!$result) echo  mysql_error();
				}			
				
				echo '<div style="padding:20px; font-family:verdana; margin:auto; width:400px; margin-top:100px;background:#afa; text-align:center; font-size:10pt;">You were trying to login as '.$user_profile['name'].'. Gausipp.com is for <strong>girls only</strong>! If you want to preview the website, you can visit <a href="http://gausipp.roopunk.com">our test area</a></div>';
				
				
			}*/
			else  // else go to the login url
			{
				echo '<script>window.location = "'.$loginUrl.'"; </script>';
			}
			
		}
		
		
	}
?>